﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UIControls
{
    /// <summary>
    /// Displays a list of images one after the other.
    /// </summary>
    public partial class ImagePane : UserControl
    {
        public ImagePane()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Contains, in order, the list of images we need to display
        /// </summary>
        private List<PictureBox> ImageList = new List<PictureBox>();

        /// <summary>
        /// Add a new image to the current list. Can be called from any thread (not just the GUI thread).
        /// </summary>
        /// <param name="img"></param>
        public void Add(Image img)
        {
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(() => Add(img))); 
            }
            else
            {
                PictureBox box = new PictureBox();
                box.Image = img;
                box.SizeMode = PictureBoxSizeMode.Zoom;
                ImageList.Add(box);
                Controls.Add(box);

                UpdateLayout();
            }
        }

        /// <summary>
        /// Returns the count of the # of images - can be called from any thread
        /// </summary>
        public int Count
        {
            get { return ImageList.Count; }
        }

        /// <summary>
        /// Re-layout the pictures we are showing
        /// </summary>
        private void UpdateLayout()
        {
            int xoff = 0;
            foreach (PictureBox p in ImageList)
            {
                p.Left = 0;
                p.Top = xoff;

                float aspectRatio = (float)p.Image.Height / (float)p.Image.Width;
                p.Width = Width;
                p.Height = (int) (aspectRatio * p.Width);

                xoff += p.Height;
            }

            Height = xoff;
        }

        /// <summary>
        /// This panel has had its size changed. If the width has changed then
        /// we will need to do some re-layout.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);

            UpdateLayout();
        }
    }
}
